import React, { useState, useEffect } from 'react';
import { TjChart, TjCollapse, TjTable } from '@/pages/ETrade/components';
import { Select, Space } from 'antd';
import styles from './index.less';
import _ from 'lodash';
import { leftOptions, rightOptions, tableStyle } from '../../constant';
import { DimensionalDoubleSort } from '../../components/DimensionalDoubleSort';
import { features, useTablePipeline } from 'ali-react-table';
import MultilevelSelect from '../MultilevelSelect';
import { DownOutlined } from '#/utils/antdIcons';
import { getChart, getChartFilterOptions, getDeviationQuantityChart } from '../../helper';
import { useThemeChange } from '@/hooks';

const width = 160;
export const Container = ({
  // getDeparture,
  setChartFilter,
  aggregateSelect = {},
  deviationQuantityData = {},
  handleFiltrate,
  setChartHeadFilter,
  chartHeadFilter = [],
  chartFilter = [],
  columns = [],
  dataSource = [],
}) => {
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [openKeys, onChangeOpenKeys] = useState(['1']);
  const [chartData, setChartData] = useState({});
  const { theme } = useThemeChange();

  const pipeline = useTablePipeline({ components: {} })
    .input({
      dataSource,
      columns,
    })
    .primaryKey('key')
    .use(features.treeMode({ openKeys, onChangeOpenKeys }));

  const onClose = async (v) => {
    setChartHeadFilter(v);
    setVisible(false);
    // await getDeparture(v, chartFilter);
  };

  const openModal = () => {
    setVisible(true);
  };

  // 聚合
  const handleAggregate = (leftSelect, rightSelect) => {
    handleFiltrate(1, leftSelect, rightSelect);
  };

  const changeChartFilter = async (key, value) => {
    let index = chartFilter.findIndex((i) => i.value === key);
    const options = _.cloneDeep(chartFilter);
    options?.forEach((i, k) => {
      if (i.value === key) {
        i.data = value;
      }
      if (k > index) {
        i.data = undefined;
      }
    });
    const chartFilterOptions = getChartFilterOptions(options, dataSource);
    // await getDeparture(chartHeadFilter, chartFilterOptions);
    setChartFilter(chartFilterOptions);
  };

  const _filterEl = () => {
    const width = 120;
    const arr = _.cloneDeep(chartFilter);
    arr.pop();
    return arr?.map((i) => (
      <Select
        placeholder={'请选择' + i.label}
        style={{ width }}
        value={i.data}
        key={i.value}
        options={i.options}
        onChange={async (v) => {
          await changeChartFilter(i.value, v);
        }}
      />
    ));
  };

  useEffect(() => {
    if (chartFilter && dataSource) {
      setChartData(getChart(chartFilter, chartHeadFilter, dataSource, columns));
    }
  }, [chartFilter, chartHeadFilter, dataSource, columns]);

  useEffect(() => {
    setTimeout(() => {
      if (chartFilter && dataSource) {
        setChartData(getChart(chartFilter, chartHeadFilter, dataSource, columns));
      }
    }, 1);
  }, [theme]);

  return (
    <>
      <TjCollapse
        left={
          <div className={styles.left_content}>
            <div className={styles.left_head}>
              <Space size={16}>{_filterEl()}</Space>
              <MultilevelSelect visible={visible} onClose={onClose} filterList={chartHeadFilter} />
              <div style={{ width }} className={styles.left_select} onClick={openModal}>
                选择数据项
                <DownOutlined />
              </div>
            </div>
            <div className={styles.left_mains}>
              <div className={styles.left_title}>偏差率</div>
              {/* <div style={{ height: 'calc(100vh - 225px)' }}> */}
              <div className={styles.left_chart_box}>
                <TjChart option={chartData} />
              </div>
            </div>
            {/*<div>*/}
            {/*  <div className={styles.left_title}>偏差量</div>*/}
            {/*  <div style={{ height: '270px' }}>*/}
            {/*    <TjChart option={getDeviationQuantityChart(deviationQuantityData)} />*/}
            {/*  </div>*/}
            {/*</div>*/}
          </div>
        }
        right={
          <div className={styles.right_content}>
            <DimensionalDoubleSort
              leftAggregate={aggregateSelect.leftSelect}
              rightAggregate={aggregateSelect.rightSelect}
              onClick={handleAggregate}
              leftOptions={leftOptions}
              rightOptions={rightOptions}
            />
            <TjTable
              isLoading={loading}
              // ...tableStyle,
              // style={{ marginTop: 10 }}
              style={{ ...tableStyle, marginTop: 10 }}
              useOuterBorder={true}
              stickyScrollHeight={10}
              useVirtual={{ horizontal: true, vertical: true, header: false }}
              defaultColumnWidth={100}
              {...pipeline.getProps()}
            />
          </div>
        }
        rightStyles={{ width: 952, padding: '20px 24px' }}
      />
    </>
  );
};
